package com.kye.express.business.jd.address;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.jd.address.viewbinder.JDAddressViewBinder;
import com.kye.express.databinding.ActivityJdaddressListBinding;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.jd.address.JDAddressBean;
import com.kye.model.bean.user.User;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 京东地址管理界面
 * 地址选择， 地址编辑， 地址删除， 地址新增
 * todo : 待优化
 */
public class JDAddressListActivity extends BaseToolbarActivity implements JDAddressListConstract.JDAddressListView, JDAddressViewBinder.OnJDAddressListener {

    private final static String TAG_CURRENT_SELECTED_ADDRESS = "TAG_CURRENT_SELECTED_ADDRESS";
    public final static int REQUEST_CODE_ADDRESS_ADD_EDIT = 2000;
    public final static int RESULT_CODE_ADDRESS_SELECT = 1000; // 选择了地址
    public final static int RESULT_CODE_ADDRESS_UPDATE = 1001; // 更新了地址（删除，编辑，新增)
    private ActivityJdaddressListBinding binding;
    private MultiTypeAdapter adapter;
    private JDAddressListConstract.JDAddressListPresenter presenter;
    private User userInfo;
    private Dialog dialog;
    private JDAddressBean currentSelectedAddress;
    private MaterialDialog showDeleteAddessDialog;
    private int resultCode = Activity.RESULT_CANCELED; // 默认取消

    public static void startActivity(Activity activity, int requestCode, JDAddressBean currentSelectedAddress) {
        Intent intent = new Intent(activity, JDAddressListActivity.class);
        intent.putExtra(TAG_CURRENT_SELECTED_ADDRESS, currentSelectedAddress);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            currentSelectedAddress = getIntent().getParcelableExtra(TAG_CURRENT_SELECTED_ADDRESS);
        } else {
            currentSelectedAddress = savedInstanceState.getParcelable(TAG_CURRENT_SELECTED_ADDRESS);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_jdaddress_list);
        presenter = new JDAddressListConstract.JDAddressListPresenter();
        ToolbarManager.setToolbar(this, binding.toolbar);
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(TAG_CURRENT_SELECTED_ADDRESS, currentSelectedAddress);
    }

    private void initViews(Bundle savedInstanceState) {
        adapter = new MultiTypeAdapter();
        adapter.register(JDAddressBean.class, new JDAddressViewBinder(this));
        binding.addresses.setLayoutManager(new LinearLayoutManager(this));
        binding.addresses.setAdapter(adapter);
    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.addAddress)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 新增地址
                         */
                        JDAddressAddEditActivity.startActivity(JDAddressListActivity.this, REQUEST_CODE_ADDRESS_ADD_EDIT, null);
                    }
                });
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.refreshInit(userInfo, currentSelectedAddress);
            }
        });
    }

    private void initData(Bundle savedInstanceState) {
        presenter.bind(this);
        Intent data = new Intent();
        setResult(resultCode, data);
    }

    @Override
    public void onUser(User user) {
        this.userInfo = user;
        binding.statusLayout.showLoadingView();
    }

    @Override
    public void refreshInitSuccess(List<JDAddressBean> jdAddressBeans) {
        binding.statusLayout.showContentView();
        adapter.setItems(jdAddressBeans);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void refreshInitServerFailed(String msg) {
        binding.statusLayout.showErrorServerView();
        ToastManager.show(this, msg);
    }

    @Override
    public void refreshInitNetFailed(String message) {
        binding.statusLayout.showErrorNetworkView();
        ToastManager.show(this, message);
    }

    @Override
    public void onSelectAddress(JDAddressBean jdAddressBean) {
        currentSelectedAddress = jdAddressBean;
        Intent intent = new Intent();
        intent.putExtra("data", jdAddressBean); // 当前选中的地址
        ArrayList<JDAddressBean> jdAddressBeanList = (ArrayList<JDAddressBean>) adapter.getItems();
        intent.putParcelableArrayListExtra("datas", jdAddressBeanList); // 所有的地址列表
        resultCode = RESULT_CODE_ADDRESS_SELECT;
        setResult(resultCode, intent);
    }

    @Override
    public void onBackPressed() {
        if (resultCode == RESULT_CODE_ADDRESS_UPDATE) {
            // 当前列表有更新操作，添加，删除，编辑,返回最新的列表数据
            ArrayList<JDAddressBean> jdAddressBeanList = (ArrayList<JDAddressBean>) adapter.getItems();
            /**
             * 处理是否删除了选中的地址
             */
            Observable.fromIterable(jdAddressBeanList)
                    .subscribeOn(Schedulers.io())
                    .any(new Predicate<JDAddressBean>() {
                        @Override
                        public boolean test(JDAddressBean jdAddressBean) throws Exception {
                            if (currentSelectedAddress == null) {
                                return false;
                            }
                            return currentSelectedAddress.getId().equals(jdAddressBean.getId());
                        }
                    })
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            if (!aBoolean) {
                                currentSelectedAddress = null;
                                Intent intent = new Intent();
                                intent.putExtra("data", currentSelectedAddress);
                                intent.putParcelableArrayListExtra("datas", jdAddressBeanList);
                                setResult(resultCode, intent);
                            } else {
                                Intent intent = new Intent();
                                intent.putExtra("data", currentSelectedAddress);
                                intent.putParcelableArrayListExtra("datas", jdAddressBeanList);
                                setResult(resultCode, intent);
                            }
                            finish();
                        }
                    });
            return;
        } else {
            finish();
        }
    }

    @Override
    public void onEditAddress(JDAddressBean jdAddressBean) {
        /**
         * todo : 编辑地址
         */
        JDAddressAddEditActivity.startActivity(JDAddressListActivity.this, REQUEST_CODE_ADDRESS_ADD_EDIT, jdAddressBean);
    }

    @Override
    public void onDeleteAddress(JDAddressBean jdAddressBean) {
        showDeleteAddessDialog(jdAddressBean);
    }

    private void showDeleteAddessDialog(JDAddressBean jdAddressBean) {
        showDeleteAddessDialog = new MaterialDialog.Builder(JDAddressListActivity.this)
                .title("删除地址")
                .content("确定删除当前地址?")
                .positiveText("确定")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        /**
                         * todo : 删除地址
                         */
                        presenter.deleteAddress(userInfo, jdAddressBean);
                        showDeleteAddessDialog.dismiss();
                    }
                })
                .positiveColor(getResources().getColor(R.color.purple_0))
                .negativeText("取消")
                .negativeColor(getResources().getColor(R.color.black_666))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showDeleteAddessDialog.dismiss();
                    }
                })
                .backgroundColor(getResources().getColor(R.color.window_background))
                .show();
        showDeleteAddessDialog.setCancelable(false);
    }

    @Override
    public void deleteAddressSuccess(OpenApiResult<Object> result, String s) {
        if (resultCode != RESULT_CODE_ADDRESS_SELECT) {
            resultCode = RESULT_CODE_ADDRESS_UPDATE; // todo : 设置更新标志
        }
        binding.statusLayout.showLoadingView();
        ToastManager.show(this, s);
    }

    @Override
    public void deleteAddressServerFailed(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void deleteAddressNetFailed(String message) {
        ToastManager.show(this, message);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ADDRESS_ADD_EDIT && resultCode == Activity.RESULT_OK) {
            if (this.resultCode != RESULT_CODE_ADDRESS_SELECT) {
                this.resultCode = RESULT_CODE_ADDRESS_UPDATE; // todo : 设置更新标志
            }
            binding.statusLayout.showLoadingView();
        }
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(this, dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }
}
